package agent

import (
	"os"
	"path"
	"strconv"
	"time"
	"wf-deploy-agent/cluster"
	"wf-deploy-agent/conf"
	"wf-deploy-agent/infra"
	"wf-deploy-agent/registry"
	"wf-deploy-agent/router"
	"wf-deploy-agent/task"
	"wf-deploy-agent/util"
	"wf-deploy-agent/worker"
)

func init() {
	createFS()
	createPid()
}

func createFS() {
	err := util.MkdirNX(conf.GetFileDir(), conf.GetBackupDir(), conf.GetPluginDir())
	if err != nil {
		infra.Logger.Fatalln(err)
	}
}

func createPid() {
	fpid := ""
	spid := strconv.Itoa(os.Getpid())
	for i := 0; i < 20; i++ {
		pidf := path.Join(conf.GetBaseDir(), "pid")
		if err := os.WriteFile(pidf, []byte(spid), 0666); err != nil {
			continue
		}

		bytes, err := os.ReadFile(pidf)
		if err != nil {
			continue
		}

		fpid = string(bytes)
		if spid == fpid {
			break
		} else {
			<-time.After(100 * time.Millisecond)
		}
	}

	if spid != fpid {
		infra.Logger.Fatalln("create pid failed!")
	}
}

func Run() {
	//开启HTTP服务
	router.Start()
	//注册和缓存服务实例
	registry.Start()
	//开始集群同步
	cluster.Sync()
	//开启定时任务
	task.Start()
	//开始订阅指令
	worker.Start()
}
